package app.service;

import app.mapper.LoginMapper;
import app.tools.redis.RedisTool;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
    @Autowired
    private LoginMapper mapper;
    @Autowired
    private RedisTool tool;

    private static RSA rsa = new RSA();

    public JSONObject login(String username, String password) {
        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
            return null;
        }
        // 开始解密过程
        username = Base64.decodeStr(username);
        password = Base64.decodeStr(password);
        // 生成cookie
        String publicKey = rsa.getPublicKeyBase64();
        JSONObject json = new JSONObject();
        JSONObject info = new JSONObject();
        info.put("name", username);
        info.put("password", password);
        String encryptBase64 = rsa.encryptBase64(JSONObject.toJSONString(info), KeyType.PublicKey);// 公钥加密
        json.put("p_k", publicKey);// 把公钥传输给客户端
        // 私钥保存到服务器
        tool.setStrValue(username, rsa.getPublicKeyBase64());// 前端传来需要先解码
        json.put("token", encryptBase64);// 将密文传输到客户端
        return json;
    }
}
